<template>
  <div v-loading.fullscreen.lock="loading">
    <el-form label-width="110px" label-position="right" size="small" ref="form" :rules="formRules" :model="formParams">
      <div class="box-card">
        <div class="small-title">出库信息</div>
        <div class="box-form small-form-item">
          <el-form-item label="出库仓库" prop="wareHouseId">
            <el-select clearable placeholder="请选择出库仓库" v-model="formParams.wareHouseId" @change="changeWareHouseId" v-if="!formParams.billId">
              <el-option v-for="item in warehouseList" :value="item.key" :label="item.label" :key="item.key"></el-option>
            </el-select>
            <div class="text" v-else>{{formParams.wareHouseName}}</div>
          </el-form-item>
          <el-form-item label="运输方式" prop="transportType">
            <el-select clearable placeholder="请选择运输方式" v-model="formParams.transportType">
              <el-option :value="1" label="陆运"></el-option>
              <el-option :value="2" label="船运"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车牌号" prop="plateNumber" v-if="formParams.transportType===1">
            <el-input placeholder="请输入车牌号" clearable v-model="formParams.plateNumber"></el-input>
          </el-form-item>
          <el-form-item label="船号" prop="shipNumber" v-if="formParams.transportType===2">
            <el-input placeholder="请输入船号" maxlength="20" clearable v-model="formParams.shipNumber"></el-input>
          </el-form-item>
          <el-form-item label="预计到库时间" prop="estimateOutDate">
            <el-date-picker v-model="formParams.estimateOutDate" :disabledDate="disabledDate" placeholder="请选择预计到库时间"></el-date-picker>
          </el-form-item>
        </div>
      </div>
      <div class="box-card">
        <div class="small-title">货物信息</div>
        <div class="box-form small-form-item" v-for="(item, index) in formParams.goods" :key="index">
          <el-form-item label="货品名称" :prop="`goods[${index}].goodsName`" :rules="formRules.goodsName">
            <el-select clearable placeholder="货品名称" v-model="item.goodsName" @change="formParams.goods[index].tankId=''">
              <el-option v-for="good in goodsList" :key="good.name" :label="good.name" :value="good.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="货品重量" :prop="`goods[${index}].goodsCount`" :rules="formRules.goodsCount">
            <el-input placeholder="请输入货品重量" v-model="item.goodsCount" maxlength="10">
              <template #append>吨</template>
            </el-input>
          </el-form-item>
          <el-form-item label="出库罐号" :prop="`goods[${index}].tankId`" :rules="formRules.tankId">
            <el-select clearable placeholder="请选择出库罐号" v-model="item.tankId">
              <el-option v-for="tank in tankList" :key="tank.id" :disabled="isTankDisabled(item, tank)" :label="tank.tankNo" :value="tank.id"></el-option>
            </el-select>
          </el-form-item>
          <i class="icon el-icon-circle-plus-outline" @click="addGood" v-if="formParams.goods.length<5"></i>
          <i class="icon el-icon-remove-outline" @click="removeGood(index)" v-if="index || formParams.goods.length>=2"></i>
        </div>
      </div>
    </el-form>
    <div class="btns">
      <el-button size="small" @click="router.push({name: 'customerOutStore'})">取消</el-button>
      <el-button size="small" class="fill" type="primary" :disabled="disabled" @click="save">确认</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { queryGoodsDictionary, queryWarehouseOrCustomer, queryOilTankSelectList } from '@/api/common'
import { createCustomerOutStoreBill, getCustomerOutStoreDetail, editCustomerOutStoreBill } from '@/api/customerOutStore'
import { useRouter, useRoute } from 'vue-router'
import { defineComponent, ref, reactive, getCurrentInstance, computed } from 'vue'
import dayjs from 'dayjs'

export default defineComponent({
  name: 'customerCreate',
  setup () {
    const router = useRouter()
    const route = useRoute()
    const { proxy } = getCurrentInstance()
    const licensePlateReg = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/
    let formParams = reactive({
      goods: [{}]
    })
    let tankList = ref([])
    let formRules = reactive({
      wareHouseId: { required: true, message: '请选择出库仓库', trigger: 'change' },
      transportType: { required: true, message: '请选择运输方式', trigger: 'change' },
      plateNumber: [
        { required: true, message: '请输入车牌号', trigger: 'change' },
        { pattern: licensePlateReg, message: '请输入正确的车牌号', trigger: 'change' }
      ],
      shipNumber: { required: true, message: '请输入船号', trigger: 'change' },
      estimateOutDate: { required: true, message: '请选择预计到库时间', trigger: 'change' },
      goodsName: { required: true, message: '请选择货品', trigger: 'change' },
      goodsCount: [
        { required: true, message: '请输入货品重量', trigger: 'change' },
        { required: true, pattern: /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/, message: '正数且最多2位小数', trigger: 'change' }
      ],
      tankId: { required: true, message: '请选择出库罐号', trigger: 'change' }
    })
    let goodsList = ref([])
    let warehouseList = ref([])
    const getConfig = async () => {
      const [goodsRes, warehouseRes] = await Promise.all([queryGoodsDictionary(), queryWarehouseOrCustomer({ userType: 20 })])
      if (goodsRes.code === 200) {
        goodsList.value = goodsRes.result
      }
      if (warehouseRes.code === 200) {
        warehouseList.value = warehouseRes.result
      }
    }
    getConfig()
    let loading = ref(false)
    const getDetail = async (id) => {
      loading.value = true
      const { code, result } = await getCustomerOutStoreDetail({ id })
      loading.value = false
      if (code !== 200) return
      const { warehouseId, wareHouseName, transportType, plateNumber, estimateOutDate, goodInfos } = result
      getTankNoByWarehouseId(warehouseId)
      formParams.billId = id
      formParams.wareHouseId = warehouseId
      formParams.wareHouseName = wareHouseName
      formParams.transportType = transportType
      formParams.estimateOutDate = estimateOutDate
      formParams.plateNumber = transportType === 1 ? plateNumber : ''
      formParams.shipNumber = transportType === 2 ? plateNumber : ''
      formParams.goods = goodInfos.map(item => {
        return {
          goodsName: item.goodsName,
          goodsCount: item.goodsCount,
          tankId: item.tankId
        }
      })
    }
    if (route.query.id) {
      getDetail(route.query.id)
    }
    const changeWareHouseId = (id) => {
      formParams.goods.forEach(item => item.tankId = '')
      tankList.value = []
      getTankNoByWarehouseId(id)
    }
    const getTankNoByWarehouseId = async (warehouseId) => {
      const { code, result } = await queryOilTankSelectList({ warehouseId, userType: 10 })
      if (code !== 200) return
      tankList.value = result
    }
    const addGood = () => {
      formParams.goods.push({})
    }
    const removeGood = (index) => {
      formParams.goods.splice(index, 1)
    }
    let disabled = ref(false)
    const save = () => {
      proxy.$refs.form.validate(async (valid) => {
        if (!valid) return
        try {
          let params = { ...formParams }
          const { transportType, plateNumber, shipNumber, estimateOutDate } = params
          params.plateNumber = transportType === 1 ? plateNumber : shipNumber
          params.estimateOutDate = dayjs(estimateOutDate).format('YYYY-MM-DD')
          disabled.value = true
          let res
          if (params.billId) {
            res = await editCustomerOutStoreBill(params)
          } else {
            res = await createCustomerOutStoreBill(params)
          }
          if (res.code !== 200) return
          proxy.$message.success('操作成功')
          router.push({ name: 'customerOutStore' })
        } finally {
          disabled.value = false
        }
      })
    }
    const disabledDate = (time) => {
      return dayjs(dayjs(time).format('YYYY-MM-DD')).isBefore(dayjs().format('YYYY-MM-DD'))
    }
    const isTankDisabled = computed(() => {
      return function ({ goodsName }, curr) {
        return goodsName !== curr.goodsName
      }
    })
    return { router, formParams, formRules, goodsList, tankList, warehouseList, changeWareHouseId, addGood, removeGood, save, disabledDate, disabled, isTankDisabled, loading }
  }
})

</script>

<style scoped lang="less">
  @import url('@/assets/css/form-box.less');
  .icon {
    font-size: 30px;
    line-height: 35px;
    color: #cccccc;
    cursor: pointer;
    margin-left: 10px;
    &:hover {
      color: #4B7EFE;
    }
  }
  .small-form-item {
    .el-form-item {
      margin-left: 0!important;
    }
  }

  .btns {
    padding: 70px 0 0 0px;
    display: flex;
    justify-content: center;
    button {
      width: 120px;
      height: 40px;
      border-radius: 4px;
      font-size: 16px;
      line-height: 22px;
      color: #666666;
      background: #FFFFFF;
      border: 1px solid #CCCCCC;
    }
    .fill {
      background: #4B7EFE;
      color: #ffffff;
      border: none;
      &:hover {
        background: #66b1ff;
      }
    }
    .el-button + .el-button {
      margin-left: 44px;
    }
  }
</style>
